<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>Hello XMatrix</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<script src="js/jquery.min.js"></script>
		<!--标准mui.css-->
		<link rel="stylesheet" href="css/mui.min.css">
		<!--App自定义的css-->
		<!--<link rel="stylesheet" type="text/css" href="../css/app.css" />-->
		<style>
			header {
				border-radius: 50px;
				width: 40%;
				margin-right: 30%;
				margin-left: 30%;
				margin-top: 5px;
			}
			header span {
				float: right;
			}
			.mui-card .mui-control-content {
				padding: 10px;
			}
			
			.mui-control-content {
				height: 950px;
			}
			
			.field-contain label{
			    width: auto;
			    padding-right: 0;
			}
					
			.field-contain input[type='text']{
			    width: 40px;
			    height: 30px;
			    padding: 5px 0;
			    float: none;
			    text-align: center;
			}
			h4,p {
				text-align: center;
			}
			.qrcode {
				/*position: absolute;*/
				top: 50px;
				/*left: 50%;*/
				width: 100%;
				/*-webkit-transform: translate(-50%, 0);
				transform: translate(-50%, 0);*/
				text-align: center;
			}
			.qrcode img {
				margin: 0 auto;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<!-- <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a> -->
			<h1 class="mui-title">XMatrix</h1>
			<span class="mui-icon mui-icon-loop" onclick="pulldownRefresh()"></span>
		</header>
		
		<div class="mui-content">
			<div style="padding: 10px 10px;">
				<div id="segmentedControl" class="mui-segmented-control">
					<a class="mui-control-item mui-active" href="#item1">主页</a>
					<a class="mui-control-item" href="#item2">模式</a>
					<a class="mui-control-item" href="#item3">配置</a>
					<a class="mui-control-item" href="#item4">命令</a>
					<a class="mui-control-item" href="#item5">说明</a>
				</div>
			</div>
			<div  id="refreshContainer">
				<div id="item1" class="mui-control-content mui-active">
					<div id="scroll" class="mui-scroll-wrapper">
						<div class="mui-input-row">
							<label>设备</label>
							<input type="text" class="mui-input-clear serviceAddress" name="serviceAddress" value="XMatrix" placeholder="请输入设备IP">
						</div>
						
						<div class="mui-button-row">
							<button type="button" class="mui-btn mui-btn-primary" onclick="connect()">连接</button>&nbsp;&nbsp;
							<span id="connectStatus" class="mui-icon mui-icon-closeempty"></span>
						</div>
						<br>
						<div class="mui-scroll">
							<div class="mui-media-object" style='margin: 0 auto; text-align: center;'>
								<img class="mui-media-object" id="emojis" onclick='clickEmoji(event);' style="height: 244px;width: 262px;margin: 0 auto; text-align: center;" src="">
							</div>
							<h1 id='out' style='margin: 0 auto; text-align: center;'></h1>
							<div style='margin: 0 auto; text-align: center;'>
								<canvas id='emoji' width='16' height='16'></canvas>
							</div>
							<div class="mui-button-row">
								<button type="button" class="mui-btn-royal mui-btn-primary" onclick="FirmwareInfo()">固件信息</button>&nbsp;&nbsp;
							</div>
						</div>
					</div>
				</div>
				<div id="item2" class="mui-control-content">
					<h5 class="mui-content-padded">模式选择</h5>
					<div class="mui-card">
						<form class="mui-input-group">
							<div class="mui-input-row mui-radio">
								<label>时钟</label>
								<input name="radio-mode" onclick="changeMode(1)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>日期</label>
								<input name="radio-mode" onclick="changeMode(2)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>时钟+日期</label>
								<input name="radio-mode" onclick="changeMode(3)" type="radio" checked>
							</div>
							<div class="mui-input-row mui-radio">
								<label>天气</label>
								<input name="radio-mode" onclick="changeMode(4)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>代码雨</label>
								<input name="radio-mode" onclick="changeMode(5)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>B站粉丝数</label>
								<input name="radio-mode" onclick="changeMode(6)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>时光回溯</label>
								<input name="radio-mode" onclick="changeMode(7)" type="radio" >
							</div>
						</form>
					</div>
					<div class="mui-button-row">
						<button type="button" class="mui-btn mui-btn-purple" onclick="FlashBack()">时光回溯</button>
						<button type="button" class="mui-btn mui-btn-primary" onclick="nextMode()">模式Next</button>
						<button type="button" class="mui-btn mui-btn-success" onclick="configSave()">保存配置</button>
					</div>
					<br>
					<h4>时钟风格</h4>
					<div class="mui-card">
						<form class="mui-input-group">
							<div class="mui-input-row mui-radio">
								<label>HH:mm:ss</label>
								<input name="radio-clock" onclick="clockMode(1)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>HH:mm</label>
								<input name="radio-clock" onclick="clockMode(2)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>emoji HH:mm</label>
								<input name="radio-clock" onclick="clockMode(3)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>emoji HH:mm</label>
								<input name="radio-clock" onclick="clockMode(4)" type="radio">
							</div>
						</form>
					</div>
					<h4>日期风格</h4>
					<div class="mui-card">
						<form class="mui-input-group">
							<div class="mui-input-row mui-radio">
								<label>MM/DD</label>
								<input name="radio-date" onclick="DateModel(1)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>emoji MM-DD</label>
								<input name="radio-date" onclick="DateModel(2)" type="radio">
							</div>
						</form>
					</div>
					<h4>切换风格</h4>
					<div class="mui-card">
						<form class="mui-input-group">
							<div class="mui-input-row mui-radio">
								<label>上下滑动</label>
								<input name="radio-loop" onclick="LoopModel(1)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>渐隐渐显</label>
								<input name="radio-loop" onclick="LoopModel(2)" type="radio">
							</div>
						</form>
					</div>
					<h4>粉丝数风格</h4>
					<div class="mui-card">
						<form class="mui-input-group">
							<div class="mui-input-row mui-radio">
								<label>单一颜色</label>
								<input name="radio-bf" onclick="BFansModel(1)" type="radio">
							</div>
							<div class="mui-input-row mui-radio">
								<label>彩色</label>
								<input name="radio-bf" onclick="BFansModel(2)" type="radio">
							</div>
						</form>
					</div>
				</div>
				<div id="item3" class="mui-control-content">
					<div class="mui-content-padded">  
					<h4 style='margin-top:15px;'>亮度</h4>
					<div class="mui-input-row mui-input-range field-contain">
					    <div style="float:left">
					        <label >亮度：</label>
					        <input type="text" id='bt_value' value='125'>
					    </div>
					    <div style="margin-left:121px;">
					        <input type="range" id='bt' value="125" oninput='sendBrightness()' min="0" max="255" />
					    </div>
					</div>
					<h4 style='margin-top:15px;'>颜色</h4>
					<div class="mui-input-row mui-input-range field-contain">
					    <div style="float:left">
					        <label >全局：</label>
					        <input type="text" id='huea_value' name='hue_value' value='180'>
					    </div>
					    <div style="margin-left:121px;">
					        <input type="range" id='huea' name='hue_value' value="180" oninput='sendHue("a")' min="0" max="360" />
					    </div>
					</div>
					<div class="mui-input-row mui-input-range field-contain">
					    <div style="float:left">
					        <label >冒号：</label>
					        <input type="text" id='hued_value' name='hue_value' value='180'>
						</div>
						<div style="margin-left:121px;">
							<input type="range" id='hued' name='hue_value' value="180" oninput='sendHue("d")' min="0" max="360" />
						</div>
					</div>
					<div class="mui-input-row mui-input-range field-contain">
						 <div style="float:left">
							 <label >小时：</label>
							 <input type="text" id='hueh_value' name='hue_value' value='180'>
						</div>
						<div style="margin-left:121px;">
							<input type="range" id='hueh' name='hue_value' value="180" oninput='sendHue("h")' min="0" max="360" />
						</div>
					</div>
					<div class="mui-input-row mui-input-range field-contain">
						 <div style="float:left">
							 <label >分钟：</label>
							 <input type="text" id='huem_value' name='hue_value' value='180'>
						</div>
						<div style="margin-left:121px;">
							<input type="range" id='huem' name='hue_value' value="180" oninput='sendHue("m")' min="0" max="360" />
						</div>
					</div>
					<div class="mui-input-row mui-input-range field-contain">
						 <div style="float:left">
							 <label >秒钟：</label>
							 <input type="text" id='hues_value' name='hue_value' value='180'>
						</div>
						<div style="margin-left:121px;">
							<input type="range" id='hues' name='hue_value' value="180" oninput='sendHue("s")' min="0" max="360" />
						</div>
					</div>
					<div class="mui-input-row mui-input-range field-contain">
						 <div style="float:left">
							 <label >星期：</label>
							 <input type="text" id='huew_value' name='hue_value' value='180'>
						</div>
						<div style="margin-left:121px;">
							<input type="range" id='huew' name='hue_value' value="180" oninput='sendHue("w")' min="0" max="360" />
						</div>
					</div>
					<div class="mui-input-row mui-input-range field-contain">
						 <div style="float:left">
							 <label >粉丝：</label>
							 <input type="text" id='hueb_value' name='hue_value' value='180'>
						</div>
						<div style="margin-left:121px;">
							<input type="range" id='hueb' name='hue_value' value="180" oninput='sendHue("b")' min="0" max="360" />
						</div>
					</div>
					</div>
					<div class="mui-button-row">
						<button type="button" class="mui-btn mui-btn-success" onclick="configSave()">保存配置</button>
					</div>
				</div>
				<div id="item4" class="mui-control-content">
					<ul class="mui-table-view">
						<li class="mui-table-view-cell mui-collapse">
							<a class="mui-navigate-right" href="#">发送命令</a>
							<div class="mui-collapse-content">
								<input type="text" class="mui-input-clear" id="customCommand" placeholder="请输入需要发送的命令">
								<div class="mui-button-row">
									<button type="button" class="mui-btn mui-btn-primary" onclick="sendCustomCommand()">发送</button>
								</div>
							</div>
						</li>
						<li class="mui-table-view-cell mui-collapse">
							<a class="mui-navigate-right" href="#">导入配置</a>
							<div class="mui-collapse-content">
								<textarea id="jsonCommand" class="mui-input-clear" rows="5" placeholder="请输入json配置"></textarea>
								<div class="mui-button-row">
									<button type="button" class="mui-btn mui-btn-success" onclick="importCustomCommand()">导入</button>
									<button type="button" class="mui-btn mui-btn-primary" onclick="exportCustomCommand()">导出</button>
								</div>
							</div>
						</li>
					</ul>
					<div class="mui-button-row" id="customButton">
							
					</div>
				</div>
				<div id="item5" class="mui-control-content">
					<h4>XMatrix像素时钟</h4>
					<p>作者：亚里士不可得</p>
					<div class="mui-content-padded">
						<div class="qrcode">
							<img id="qrcode" src="img/bcard.jpg" width="70%" />
							<a id="shortcut" style="width: 60%;margin: 15px auto;padding: 5px;" class="mui-hidden mui-btn mui-btn-block mui-btn-red">创建桌面图标</a>
						</div>
						<!--<h4 style="margin-top:10px;">mui</h4>-->
						<p>XMatrix是一个仿Awtrix Pro制作的离线版像素时钟项目，支持时钟、日期、天气、粉丝数显示等功能，
							更多详细介绍，请点击<a href="https://www.bilibili.com/video/BV1mt4y1T7Tt">XMatrix介绍视频</a>查看</p>
						<p style="text-align: center;color: #ccc;text-indent: 0;">当前版本：<span id="version">3.0</span></p>	
					</div>
					
				</div>
			</div>	
		</div>
		<script src="js/mui.min.js"></script>
		<script src="js/websocket.js"></script>
		<script>
			mui.init({
				swipeBack: true ,//启用右滑关闭功能
			});
			// 定义下拉回调函数
			function pulldownRefresh(){
				location.reload();
			}
			(function($) {
				$('#scroll').scroll({
					indicators: true //是否显示滚动条
				});
				var segmentedControl = document.getElementById('segmentedControl');
				$('.mui-input-group').on('change', 'input', function() {
					if (this.checked) {
						var styleEl = document.querySelector('input[name="style"]:checked');
						var colorEl = document.querySelector('input[name="color"]:checked');
						if (styleEl && colorEl) {
							var style = styleEl.value;
							var color = colorEl.value;
							segmentedControl.className = 'mui-segmented-control' + (style ? (' mui-segmented-control-' + style) : '') + ' mui-segmented-control-' + color;
						}
					}
				});
			})(mui);
			let connectStatus = document.getElementById('connectStatus');
			let localServiceAddress = localStorage.getItem("serviceAddress");
			let serviceAddress = "XMatrix";
			if(localServiceAddress == "null"){
				console.log('是空的');
			}else{
				console.log('不为空');
				console.log(localServiceAddress);
				$('.serviceAddress').val(localServiceAddress);
				serviceAddress = localServiceAddress;
			}
			let localCustomCommand = localStorage.getItem("customCommand");
			if(localCustomCommand != "null"){
				console.log("自定义命令："+localCustomCommand);
				$('#customCommand').val(localCustomCommand);
			}
			function nw() { return new WebSocket('ws://' + serviceAddress + ':81/', ['arduino']); }
			let ws = nw();
			function connect(){
				serviceAddress = $('.serviceAddress').val();
				//alert("连接地址："+serviceAddress);
				ws = nw();
				localStorage.setItem("serviceAddress",serviceAddress);
				if(ws.readyState === ws.CLOSED){
					mui.toast('连接失败');
					connectStatus.setAttribute("class", "mui-icon mui-icon-closeempty");
				}else if(ws.readyState === ws.OPEN){
					mui.toast('连接成功');
					connectStatus.setAttribute("class", "mui-icon mui-icon-checkmarkempty");
				}else if(ws.readyState === ws.CONNECTING){
					mui.toast('连接中');
					connectStatus.setAttribute("class", "mui-spinner");
				}
			};
			function sendCustomCommand(){
				var customCommand = $('#customCommand').val();
				if(customCommand != 'null' && customCommand != ''){
					if(customCommand != localCustomCommand){
						localStorage.setItem("customCommand",customCommand);
					}
					ws.send(customCommand);
					mui.toast('已发送:'+customCommand);
				}else{
					mui.toast('命令不能为空');
				}
			}
			function clickCustomCommand(commandStr){
				var customCommand;
				if(typeof(commandStr) === undefined || commandStr == ''){
					mui.toast('命令不能为空');
				}else{
					customCommand = commandStr.getAttribute("data-command");
					if(customCommand != 'null'){
						console.log("自定义命令："+customCommand);
						ws.send(customCommand);
						mui.toast('已发送:'+customCommand);
					}
				}
			}
			var int=self.setInterval("clock()",3000);
			function clock()
			{
				if(ws.readyState === ws.CLOSED){
					connectStatus.setAttribute("class", "mui-icon mui-icon-closeempty");
				}else if(ws.readyState === ws.OPEN){
					connectStatus.setAttribute("class", "mui-icon mui-icon-checkmarkempty");
				}else if(ws.readyState === ws.CONNECTING){
					connectStatus.setAttribute("class", "mui-spinner");
				}
			}
			ws.onopen = function () { 
				ws.send('Connect ' + new Date()); 
				connectStatus.setAttribute("class", "mui-icon mui-icon-checkmarkempty");
			}; 
			ws.onerror = function (error) { console.log('WebSocket Error ', error); }; 
			ws.onmessage = function (e) { 
				connectStatus.setAttribute("class", "mui-icon mui-icon-checkmarkempty");
				console.log('Server: ', e.data); 
				if(e.data[0]=='{'){
					console.log('json');
					var jsonOb = eval('('+e.data+')');
					var brightNess = typeof(jsonOb.brightNess)=='undefined'? 150:jsonOb.brightNess;
					var mode = typeof(jsonOb.mode)=='undefined'? 2:jsonOb.mode;
					var huea = typeof(jsonOb.huea)=='undefined'? 180:jsonOb.huea;
					var hued = typeof(jsonOb.hued)=='undefined'? 180:jsonOb.hued;
					var hueh = typeof(jsonOb.hueh)=='undefined'? 180:jsonOb.hueh;
					var huem = typeof(jsonOb.huem)=='undefined'? 180:jsonOb.huem;
					var hues = typeof(jsonOb.hues)=='undefined'? 180:jsonOb.hues;
					var huew = typeof(jsonOb.huew)=='undefined'? 180:jsonOb.huew;
					var hueb = typeof(jsonOb.hueb)=='undefined'? 180:jsonOb.hueb;
					var clockMode = typeof(jsonOb.clockMode)=='undefined'? 1:jsonOb.clockMode;
					var dateMode = typeof(jsonOb.dateMode)=='undefined'? 1:jsonOb.dateMode;
					var loopMode = typeof(jsonOb.loopMode)=='undefined'? 1:jsonOb.loopMode;
					var bFansMode = typeof(jsonOb.bFansMode)=='undefined'? 1:jsonOb.bFansMode;
					$("input[name='radio-mode']").eq(mode-1).attr('checked','checked');
					$("input[name='radio-clock']").eq(clockMode-1).attr('checked','checked');
					$("input[name='radio-date']").eq(dateMode-1).attr('checked','checked');
					$("input[name='radio-loop']").eq(loopMode-1).attr('checked','checked');
					$("input[name='radio-bf']").eq(bFansMode-1).attr('checked','checked');
					document.getElementById('bt').value=parseInt(brightNess);
					document.getElementById('bt_value').value=parseInt(brightNess);
					document.getElementById('huea').value=parseInt(huea);
					document.getElementById('huea_value').value=parseInt(huea);
					document.getElementById('hued').value=parseInt(hued);
					document.getElementById('hued_value').value=parseInt(hued);
					document.getElementById('hueh').value=parseInt(hueh);
					document.getElementById('hueh_value').value=parseInt(hueh);
					document.getElementById('huem').value=parseInt(huem);
					document.getElementById('huem_value').value=parseInt(huem);
					document.getElementById('hues').value=parseInt(hues);
					document.getElementById('hues_value').value=parseInt(hues);
					document.getElementById('huew').value=parseInt(huew);
					document.getElementById('huew_value').value=parseInt(huew);
					document.getElementById('hueb').value=parseInt(hueb);
					document.getElementById('hueb_value').value=parseInt(hueb);
						   
				}
			};
			ws.onclose = function(e){
				
			}
			let customConfig = localStorage.getItem("commandJson");
			let customObj = JSON.parse(customConfig);
			let customButtonDiv = $("#customButton");
			buttonRebuild(customObj);
			function buttonRebuild(jsonObj){
				try {
					if(jsonObj.button != 'null'){
						for (var key in jsonObj.button) {
							customButtonDiv.append("<button type='button' id='cb' class='"+jsonObj.button[key].class+"' data-command='"+jsonObj.button[key].command +"' onclick='clickCustomCommand(this)'>"+jsonObj.button[key].name+"</button>&nbsp;");
							if((parseInt(key)+1)%4 == 0){
								customButtonDiv.append("<br id='cb'><br id='cb'>");
							}
						}
					}else{
						mui.toast('json错误');
					}
				}catch(e){
					console.log('构建异常：'+e);
				}
				
			}
			function importCustomCommand(){
				var btnArray = ['取消', '确认'];
				mui.confirm('即将覆盖配置，确认导入json？', '确认提示', btnArray, function(e) {
					if (e.index == 1) {
						var newJsonCommand =  $('#jsonCommand').val();
						console.log(newJsonCommand);
						if(newJsonCommand == ''){
							mui.toast('未填入json');
						}else{
							try {
							    var jsonObj = JSON.parse(newJsonCommand);
							    if(typeof jsonObj == 'object' && jsonObj ){
							    	var x = document.getElementsByTagName("button");
									var y = document.getElementsByTagName("br");
							    	for(var i = 0;i<x.length;i++){
							    		if(x[i].id == "cb"){
							    			x[i].remove();
							    			x.length -= 1;
							    			i -= 1;
							    		}
							    	}
									for(var j = 0;j<y.length;j++){
										if(y[j].id == "cb"){
											y[j].remove();
											y.length -= 1;
											j -= 1;
										}
									}
									clear(customButtonDiv,true);
							    	buttonRebuild(jsonObj);
									localStorage.setItem("commandJson",newJsonCommand);
							    }else{
									mui.toast('json格式不正确');
							    }
							} catch(e) {
							    mui.toast('json解析异常');
							} finally {
							    //结束处理
							}
						}
					} else {
						mui.toast('取消导入');
						return;
					}
				})
				
			};
			function exportCustomCommand(){
				var jsonStr = localStorage.getItem("commandJson");
				$('#jsonCommand').val(jsonStr);
			};
			function clear(obj,test){
			  var x=obj||document.getElementsByTagName('*'),i=x.length;
			  while(i--){
			    var y=x[i].childNodes,j=y.length;
			    while(j--){
			      if(y[j].nodeType==3){
			        if(test==true){
			          y[j].nodeValue=y[j].nodeValue.replace(/\s|&nbsp;/g,'')
			        }else{
			          if(!/\S/.test(y[j].nodeValue)){y[j].parentNode.removeChild(y[j])}
			        }
			      }
			    }
			  }
			};
		</script>

	</body>

</html>